/**
 * @description  基础信息（场外基金指令）
 * @author shenhong
 */
import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { message, Input } from 'antd';
import { DATA_ENTRY, FormGroup, codeType } from '../../../../comps';
import style from '../index.less';
import investmentTypeData from '../../../../utils/enumeratedValues/investmentType';
import { isZiGuanEvir, calculateFee } from '../../../../utils/commonFunc';
import addBondValues from '../../../../utils/enumeratedValues/addBondValues';
import debounce from 'lodash/debounce';
const selectDatas = (data) => {
  const arr = [];
  if (data && data.length) {
    data.map((item) => {
      arr.push({ title: item.value, value: item.code });
    });
  }
  return arr;
};

@Form.create()
class AddBond extends PureComponent {
  static defaultProps = {
    onRef: () => {},
    portfolioOnChange: () => {},
    secucodeOnChange: () => {},
    applyMethod: () => {},
  };
  constructor() {
    super();
    this.state = {
      currentUser: {}, // 当前登录用户信息
      codeT: undefined, // 证券代码类型
      fundInfo: undefined,
      rollInCodeInfo: undefined,
      isZiGuan: false,
      isWithdrawals: false, //巨额赎回处理方式是否展示
      isDividendMethod: true, //分红方式是否展示
      salesOrganizationCodeData: [], //销售机构代码数据
      applyMethod: '1', //委托方向
      feeData: {
        //费用自动计算条件
        productId: undefined,
        portfolioid: undefined,
        tradingCode: undefined,
        exchangecode: undefined,
        sectype: 'fund',
        orderside: undefined,
        price: undefined,
      },
    };
    // 绑定lodash的防抖函数，避免频繁搜索的情况
    this.getSalesOrganizationCodeData = debounce(this.getSalesOrganizationCodeData, 500);
  }
  UNSAFE_componentWillMount() {
    const { type, info } = this.props;
    let code = '0';
    if (type == '3' || type == '4' || type == 'edit') {
      code = info.trade5.isPublic;
      this.setState({ applyMethod: info.trade5.applyMethod });
    }
    let temp = isZiGuanEvir();
    let isZiGuan = !!temp; // 判断该页面是在资管被引入的，还是maat
    this.setState({
      codeT: code == '0' ? codeType.gmjj : codeType.smjj,
      isZiGuan,
    });
    if (isZiGuan) {
      this.props.dispatch({
        type: 'newFundTrade/getSalesOrganizationCodeData',
        payload: { value: '' },
        callback: (res) => {
          if (res) {
            this.initData = res.slice(0, 100); //存储初始化的100条数据
            this.setState({
              salesOrganizationCodeData: res,
            });
          } else {
            this.setState({
              salesOrganizationCodeData: [],
            });
          }
        },
      });
    }
  }
  componentDidMount() {
    this.props.onRef(this);
    const { dispatch } = this.props;
    dispatch({
      type: 'interBankBasicInfoM/getUserInfo',
      payload: localStorage.getItem('antd-pro-userId'), // 获取对当前用户信息
      callback: (res) => {
        this.setState({
          currentUser: res,
        });
      },
    });
    //这里的字典没有调用
    const {
      globalM: {
        dataDictionary: { fund_Trade_Order_apply_type = [] },
      },
    } = this.props;
    const apply_type = selectDatas(fund_Trade_Order_apply_type || []);
    this.setState({
      selectData: this.props.type == 10 ? apply_type.filter((item) => item.value != 1) : apply_type, //交易录入时只有认购 赎回
    });
  }

  //费用自动计算
  changeFee = (type, data) => {
    const {
      form: { setFieldsValue },
    } = this.formGroupThis.props;
    if (this.props.type == 3 || this.props.type == 4) return; //详情不计算
    setTimeout(() => {
      if (data == undefined) {
        setFieldsValue({ fee: undefined });
        if (type == 'tradingCode') {
          this.setState({ feeData: { ...this.state.feeData, tradingCode: undefined, exchangecode: undefined } });
        } else if (type == 'productId') {
          this.setState({ feeData: { ...this.state.feeData, productId: undefined, portfolioid: undefined } });
        } else {
          this.setState({ feeData: { ...this.state.feeData, [type]: undefined } });
        }
      } else {
        if (type == 'tradingCode') {
          this.setState({ feeData: { ...this.state.feeData, tradingCode: data.tradingCode, exchangecode: data.exchangeCode } }, () => {
            let fee = calculateFee(this.state.feeData);
            fee.then((r) => {
              setFieldsValue({ fee: r });
            });
          });
        } else {
          this.setState({ feeData: { ...this.state.feeData, [type]: data } }, () => {
            let fee = calculateFee(this.state.feeData);
            fee.then((r) => {
              setFieldsValue({ fee: r });
            });
          });
        }
      }
    }, 100);
  };

  //销售机构代码模糊搜索
  getSalesOrganizationCodeData = (e) => {
    this.setState({
      salesOrganizationCodeData: [],
    });

    if (e) {
      this.props.dispatch({
        type: 'newFundTrade/getSalesOrganizationCodeData',
        payload: { value: e },
        callback: (res) => {
          if (res) {
            this.setState({
              salesOrganizationCodeData: res,
            });
          } else {
            this.setState({
              salesOrganizationCodeData: [],
            });
          }
        },
      });
    } else {
      this.setState({
        salesOrganizationCodeData: this.initData ? this.initData : [],
      });
    }
  };

  // 基金类型改变
  changeCodeType = (e) => {
    if (e) {
      this.props.fundType(e);
    }
    this.fundIdSet.setSelect(null);
    this.setState({
      fundInfo: undefined,
      rollInCodeInfo: undefined,
    });
    if (e == '0') {
      this.setState({
        codeT: codeType.gmjj,
      });
    } else if (e == '1') {
      this.setState({
        codeT: codeType.smjj,
      });
    }
  };

  //证券代码改变时根据交易方向更改投资类型
  changeinvestmentType = () => {
    const {
      form: { getFieldValue },
    } = this.formGroupThis.props;
    if (getFieldValue('applyMethod') == 2) {
      this.props.form.setFieldsValue({
        investmentType: this.props.position?.investmentType,
      });
    } else {
      this.props.form.setFieldsValue({
        investmentType: 'FVTPL',
      });
    }
  };

  // 委托方向改变事件
  changeapplyMethod = (e) => {
    const { type } = this.props;
    const {
      form: { setFieldsValue },
    } = this.formGroupThis.props;
    if (e && e !== undefined) {
      if (e.value == '2' || e.value == '5') {
        this.setState({
          isWithdrawals: true,
          isDividendMethod: false,
        });
      } else if (e.value == '0' || e.value == '1' || e.value == '6') {
        this.setState({
          isWithdrawals: false,
          isDividendMethod: true,
        });
      }
      if (type == '3' || type == '4' || type == 'edit') {
        //编辑，详情的时候不清除申请份额和申请金额
        return;
      }
      if (e.value == '2') {
        setFieldsValue({
          applyAmount: '',
          investmentType: this.props.position?.investmentType,
        });
      } else {
        setFieldsValue({
          applyNum: '',
          investmentType: 'FVTPL',
        });
      }
      this.setState({ rollInCodeInfo: undefined, applyMethod: e.value });
    }
  };

  // 表单内容
  formContent = () => {
    const { info, type, listId } = this.props;
    const { currentUser, codeT, applyMethod, isZiGuan, isWithdrawals, isDividendMethod, salesOrganizationCodeData } = this.state;
    const gsm = [
      { value: '0', title: '公募' },
      { value: '1', title: '私募' },
    ];
    const method = type == 'edit' ? info.trade5.applyMethod : undefined;
    return (
      <FormGroup
        dataSource={[
          type == '10'
            ? {
                dataIndex: 'listId',
                type: DATA_ENTRY.SERIESPRODUCTGROUP,
                rules: [{ required: true, message: '请选择系列产品!' }],
                disabled: true,
                initialValue: listId,
                onChange: (e) => {
                  this.props.seriesProductsOnChange(e?.value);
                }, // 向外抛处系列产品id
                span: 24,
              }
            : {
                dataIndex: ['productId', 'portfolioId'],
                type: DATA_ENTRY.PRODUCTGROUPSEP,
                multipleGroup: false,
                initialValue: type == '3' || type == '4' || type == 'edit' ? [info.trade5.productId, info.trade5.portfolioId] : undefined,
                disabled: type == '3' || type == '4' || type == 'edit' ? true : false,
                rules: [[{ required: true, message: '请选择产品!' }], [{ required: true, message: '请选择组合!' }]],
                groupOnChange: (e) => {
                  this.props.portfolioOnChange(e?.key); // 向外抛处组合id
                  this.props.portfolioCode(e?.info.portfolioCode); //向外抛出组合code
                  this.changeFee('portfolioid', e?.key);
                },
                productOnChange: (e) => {
                  this.props.productCode(e?.info.portfolioCode); //向外抛出产品code
                  this.changeFee('productId', e?.key);
                },
                authority: 'write', // 可写权限
                exist: 1,
                span: 24,
                tradeModel: type == '1' || type == '2' ? ['BOOKKEEPING_MODE', 'COMMAND_MODE'] : undefined, //不包含估值解析和估值对接的产品
              },
          {
            title: '基金类型',
            dataIndex: 'fundTypeSelect',
            type: DATA_ENTRY.SELECT,
            dataSource: gsm,
            initialValue: type == '3' || type == '4' || type == 'edit' ? info.trade5.isPublic : '0',
            disabled: type == '3' || type == '4' || type == 'edit' ? true : false,
            rules: [{ required: true, message: '请选择基金类型' }],
            multiple: false,
            placeholder: '请选择',
            onChange: this.changeCodeType,
            onRef: (ref) => (this.formGroupThis = ref),
            span: 12,
          },
          {
            //公募基金
            hide: codeT != codeType.gmjj,
            title: '基金代码',
            dataIndex: 'fundId',
            type: DATA_ENTRY.SECURITIESCODE,
            initialValue: type == 3 || type == '4' || type == 'edit' ? info.trade5.exchangeCode + '-' + info.trade5.fundId : '',
            codeType: codeType.gmjj,
            queryItems: { exchangeCode: 921 },
            disabled: type == '3' || type == '4' || type == 'edit' ? true : false,
            onChange: (e) => {
              if (e) {
                this.setState({ fundInfo: e });
                this.props.secucodeOnChange(e);
                this.changeFee('tradingCode', e);
              } else {
                this.props.secucodeOnChange(undefined);
                this.changeFee('tradingCode', undefined);
              }
            },
            rules: [{ required: true, message: '请选择基金代码!' }],
            onRef: (ref) => (this.fundIdSet = ref),
            span: 12,
          },
          {
            //私募基金
            hide: codeT == codeType.gmjj,
            title: '基金代码',
            dataIndex: 'fundId',
            type: DATA_ENTRY.SECURITIESCODE,
            initialValue: type == 3 || type == '4' || type == 'edit' ? info.trade5.exchangeCode + '-' + info.trade5.fundId : '',
            codeType: codeType.smjj,
            disabled: type == '3' || type == '4' || type == 'edit' ? true : false,
            onChange: (e) => {
              if (e) {
                this.setState({ fundInfo: e });
                this.props.secucodeOnChange(e);
                this.changeFee('tradingCode', e);
              } else {
                this.props.secucodeOnChange(undefined);
                this.changeFee('tradingCode', undefined);
              }
            },
            rules: [{ required: true, message: '请选择基金代码!' }],
            onRef: (ref) => (this.fundIdSet = ref),
            span: 12,
          },
          ...(!isZiGuan && this.props.type != '10'
            ? [
                {
                  title: '投资类型',
                  dataIndex: 'investmentType',
                  type: DATA_ENTRY.SELECT,
                  initialValue: type == '3' || type == '4' || type == 'edit' ? info.trade5.investmentType : 'FVTPL',
                  disabled: type == '3' || type == '4' || type == 'edit' ? true : applyMethod == 2 ? true : false,
                  dataSource: investmentTypeData,
                  allowClear: true,
                  rules: [{ required: false, message: '请选择' }],
                  span: 12,
                },
              ]
            : []),
          {
            title: '委托方向', // 显示名称
            dataIndex: 'applyMethod', // Form识别的Item ID
            type: DATA_ENTRY.TRADINGDIRECT,
            businessType: '5',
            // initialValue:(type == '3' || type == '4' || type == 'edit') ? info.trade5.applyMethod : type == 10 ? '0' : '1',
            initialValue: type == '3' || type == '4' || type == 'edit' ? info.trade5.applyMethod : '1',
            onChange: (e) => {
              this.props.applyMethod(e);
              this.changeapplyMethod(e);
              this.changeFee('orderside', e?.value);
            },
            disabled: type == '3' || type == '4' || type == 'edit' ? true : false,
            rules: [{ required: true, message: '请选择申请类型!' }],
            appType: type == '3' || type == 'edit' ? '2' : '0',
            span: 12,
          },
          {
            title: '申请金额',
            dataIndex: 'applyAmount',
            type: DATA_ENTRY.INPUTNUMBER,
            placeholder: '请输入',
            precision: 2,
            min: 0.01,
            max: 999999999999,
            splitStyle: true,
            initialValue: type == '3' || type == '4' || type == 'edit' ? info.trade5.applyAmount : '',
            disabled: type == '3' || type == '4' || type == 'edit' ? (type == 'edit' ? false : true) : applyMethod !== '2' ? false : true,
            rules: [
              { required: (applyMethod !== '2' && applyMethod !== '5') || method == 2 ? true : false, message: `请输入申请金额` },
              { pattern: /^(?!(0[0-9]{0,}$))[0-9]{1,}[.]{0,}[0-9]{0,}$/, message: '申请金额须大于0' },
            ],
            unit: '元',
            span: 12,
            onBlur: (e) => this.changeFee('price', e.target?.value ? Number(e.target?.value) : undefined),
          },
          type == 10
            ? {
                title: '申请份额',
                dataIndex: 'applyNum',
                type: DATA_ENTRY.INPUTNUMBER,
                min: 1,
                initialValue: '',
                precision: 0,
                placeholder: '请输入',
                rules: [{ required: true, message: `请输入申请份额` }],
                disabled: false,
                span: 12,
              }
            : {
                title: '申请份额',
                dataIndex: 'applyNum',
                type: DATA_ENTRY.INPUTNUMBER,
                // precision:2,
                min: 1,
                initialValue: type == '3' || type == '4' || type == 'edit' ? info.trade5.applyNum : '',
                placeholder: '请输入',
                rules: [
                  { required: applyMethod == '2' || applyMethod == '5' || (method != 2 && method !== undefined) ? true : false, message: `请输入申请份额` },
                  { pattern: /^(?!(0[0-9]{0,}$))[0-9]{1,}[.]{0,}[0-9]{0,}$/, message: '申请份额须大于0' },
                ],
                disabled: type == '3' || type == '4' || type == 'edit' ? (type == 'edit' ? false : true) : applyMethod == '2' || applyMethod == '5' ? false : true,
                span: 12,
              },
          ...(isWithdrawals
            ? [
                {
                  title: '巨额赎回处理方式',
                  dataIndex: 'withdrawals',
                  type: DATA_ENTRY.SELECT,
                  initialValue: type == '3' || type == '4' || type == 'edit' ? info.trade5.withdrawals : undefined,
                  disabled: type == '3' || type == '4' || type == 'edit' ? true : false,
                  dataSource: addBondValues.withdrawals,
                  allowClear: true,
                  rules: [{ required: true, message: '请选择' }],
                  span: 12,
                },
              ]
            : []),
          ...(isDividendMethod
            ? [
                {
                  title: '分红方式',
                  dataIndex: 'dividendMethod',
                  type: DATA_ENTRY.SELECT,
                  initialValue: type == '3' || type == '4' || type == 'edit' ? info.trade5.dividendMethod : undefined,
                  disabled: type == '3' || type == '4' || type == 'edit' ? true : false,
                  dataSource: addBondValues.dividendMethod,
                  allowClear: true,
                  rules: [{ required: true, message: '请选择' }],
                  span: 12,
                },
              ]
            : []),
          ...(applyMethod == '5'
            ? [
                codeT == codeType.gmjj
                  ? {
                      title: '转入证券',
                      dataIndex: 'rollInCode',
                      type: DATA_ENTRY.SECURITIESCODE,
                      initialValue: type == 3 || type == '4' || type == 'edit' ? info.trade5.rollnExchangeCode + '-' + info.trade5.rollInCode : '',
                      queryItems: { exchangeCode: 921 },
                      codeType: codeType.gmjj,
                      disabled: type == '3' || type == '4' || type == 'edit' ? true : false,
                      onChange: (e) => {
                        if (e) {
                          this.setState({
                            rollInCodeInfo: e,
                          });
                        }
                      },
                      rules: [{ required: true, message: '请选择转入证券!' }],
                      onRef: (ref) => (this.fundIdSet = ref),
                      span: 12,
                    }
                  : {
                      title: '转入证券',
                      dataIndex: 'rollInCode',
                      type: DATA_ENTRY.SECURITIESCODE,
                      initialValue: type == 3 || type == '4' || type == 'edit' ? info.trade5.rollnExchangeCode + '-' + info.trade5.rollInCode : '',

                      codeType: codeType.smjj,
                      disabled: type == '3' || type == '4' || type == 'edit' ? true : false,
                      onChange: (e) => {
                        if (e) {
                          this.setState({
                            rollInCodeInfo: e,
                          });
                        }
                      },
                      rules: [{ required: true, message: '请选择转入证券!' }],
                      onRef: (ref) => (this.fundIdSet = ref),
                      span: 12,
                    },
              ]
            : []),
          {
            title: '下达人',
            dataIndex: 'orderman',
            type: DATA_ENTRY.INPUT,
            placeholder: '请输入',
            rules: [{ required: true, message: `请输入剩余票面金额` }],
            initialValue: type == '3' || type == '4' || type == 'edit' ? info.userName : currentUser.name,
            disabled: true,
            span: 12,
          },
          ...(isZiGuan
            ? [
                {
                  title: '销售机构代码',
                  dataIndex: 'salesOrganizationCode',
                  type: DATA_ENTRY.SELECT,
                  initialValue: type == '3' || type == '4' || type == 'edit' ? info.trade5.salesOrganizationCode : undefined,
                  disabled: type == '3' || type == '4' || type == 'edit' ? true : false,
                  dataSource: salesOrganizationCodeData,
                  allowClear: true,
                  showSearch: true,
                  onSearch: (e) => {
                    this.getSalesOrganizationCodeData(e);
                  },
                  rules: [{ required: true, message: '请选择' }],
                  filterOption: false,
                  span: 12,
                },
              ]
            : []),
          {
            title: '费用',
            dataIndex: 'fee',
            type: DATA_ENTRY.INPUTNUMBER,
            placeholder: '请输入',
            min: 0,
            precision: 2,
            initialValue: type == '3' || type == '4' || type == 'edit' ? info.trade5.fee : '',
            splitStyle: true,
            disabled: type == '3' || type == '4' || type == 'edit' ? true : false,
            unit: '元',
            span: 12,
            hide: type == 10 ? false : true,
          },
          {
            dataIndex: 'remark',
            type: DATA_ENTRY.INPUT,
            title: '备注',
            disabled: type == '3' || type == '4' || type == 'edit' ? true : false,
            initialValue: type == '3' || type == '4' || type == 'edit' ? info.trade5.remark : '',
            placeholder: '请输入',
            showTextArea: true,
            autosize: { minRows: 2, maxRows: 2 },
            span: 24,
          },
        ]}
        autoLayout={false}
      />
    );
  };

  // 清空表单
  reset = () => {
    const { form } = this.formGroupThis.props;
    const { type } = this.props;
    form.resetFields();
    this.changeapplyMethod(type == 10 ? { value: '0' } : { value: '1' });
    this.setState({ codeT: 'fondGM' });
  };
  // 获取校验并获取表单的值
  getInfo = () => {
    const {
      form: { validateFields },
    } = this.formGroupThis.props;
    let query = undefined;
    validateFields((err, fieldsValue) => {
      if (!err) {
        if (fieldsValue.rollInCode == fieldsValue.fundId) {
          message.error('基金代码和转入基金不能相同');
          return;
        }
        query = fieldsValue;
        query.fundInfo = this.state.fundInfo;
        query.rollInCodeInfo = this.state.rollInCodeInfo;
        if (this.props.type != 10) query.fee = 0; // 费用计算逻辑未完全梳理清楚，后续用户有真正需求时再添加费用计算相关逻辑
      }
    });
    return query;
  };

  render() {
    return <div className={style.info}>{this.formContent()}</div>;
  }
}
// props类型

export default connect(({ interBankBasicInfoM, dictionaryM, newFundTrade, globalM }) => ({
  interBankBasicInfoM,
  dictionaryM,
  newFundTrade,
  globalM,
}))(AddBond);
